import { NativeModules } from 'react-native';
import Log from '../../common/log';
import { isIOS } from '../../constant';

const request = (
  data: any,
  successCb: (res: string) => void,
  errorCb: (msg: string) => void
): void => {
  NativeModules.ShellExec.request(data, successCb, errorCb);
};

const requestByShortConnection = (
  url: string,
  data: any,
  successCb: (res: string) => void,
  errorCb: (msg: string) => void
): void => {
  NativeModules.ShellExec.requestByShortConnection(
    url,
    data,
    successCb,
    errorCb
  );
};

const setBackupIPs = (ips: string, host: string): void => {
  try {
    if (NativeModules.ShellExec.setBackupIPs) {
      NativeModules.ShellExec.setBackupIPs(ips, host);
    }
  } catch (error) {
    Log.e('set backup ips error', error);
  }
};

const clearTask = (): void => {
  if (NativeModules.ShellExec.clearTask) {
    NativeModules.ShellExec.clearTask();
  }
};

const makeSureLongLinkConnected = (): void => {
  if (NativeModules.ShellExec.makeSureLongLinkConnected) {
    NativeModules.ShellExec.makeSureLongLinkConnected();
  }
};

const destroyMars = (): void => {
  if (NativeModules.ShellExec.destroyMars) {
    NativeModules.ShellExec.destroyMars();
  }
};

const pushCallback = (taskId: number): void => {
  if (NativeModules.ShellExec.pushCallback) {
    if (isIOS) {
      NativeModules.ShellExec.pushCallback(
        taskId,
        (): void => {},
        (): void => {}
      );
    } else {
      NativeModules.ShellExec.pushCallback(taskId);
    }
  }
};

const hasModule = (): boolean => !!NativeModules.ShellExec;

export default {
  request,
  requestByShortConnection,
  hasModule,
  setBackupIPs,
  clearTask,
  pushCallback,
  makeSureLongLinkConnected,
  destroyMars
};
